-- local Fireball = require "Fireball"
-- Tower.lua
-- 塔类
local Tower = {}
Tower.__index = Tower
local playeronescore =0
local playertwoscore =0
function Tower:new(x, y,side,fixedindex,towerType,towerid, range, damage, attackSpeed)
    local tower = {
        x = x,
        y = y,
        side = side, -- 那个玩家的塔
        fixedindex = fixedindex, -- 对应地图固定位置的编号
        range = range, -- 攻击范围
        damage = damage, -- 攻击力
        -- attackCooldown = attackCooldown, -- 攻击间隔
        cooldownTimer = 0, -- 冷却计时器
        towerType =towerType, -- 塔类型
        lastTarget = nil,  -- 存储上一次攻击的目标
        specialEffect  ='normal',  -- 攻击类型  normal是正常攻击， groupattack是群体攻击， buffatk  增加攻击力 ， slow 减速敌人， buffspeed 减速敌人
        attackSpeed = attackSpeed,  -- 攻击速度（每秒攻击次数）
        towerid =towerid,   --塔添加的编号自增
        atk_add_rate =1,    --攻击加成率
        atk_global =0,    --全局攻击加成。
        atk_original_global =0,    --记录原始全局攻击加成。
        atkEffects = {}, -- 存储临时加攻击效果
        atk_speed_add_rate =0,    --攻击速度加成率。
        atk_speed_global =0,    --全局攻击速度加成。
        atk_speed_original_global =0,    --记录原始全局攻击速度加成。
        atkSpeedEffects = {}, -- 存储临时加攻击速度效果

        dec_speed_time =0,    --duration  持续时间
        dec_speed_slow =0,    -- 减速效果0.1
        dec_speed_slow_global =0,    -- 全局减速效果
        dec_speed_original_global =0,    -- 记录原始减速效果
        
    }
    -- if towerType ==1 then
    -- 群体攻击测试
    --    tower.specialEffect  ='groupattack'
    -- end

    if towerType ==1 then
        -- 增加攻击力测试
        -- tower.specialEffect  ='buffatk'
        -- tower.atk_global =0.1    --全局攻击加成。
        -- tower.atk_original_global =tower.atk_global    --记录原始全局攻击加成。

        -- 增加攻击速度测试
        tower.specialEffect  ='buffspeed'
        tower.atk_speed_global =0.1     --全局攻击速度加成。
        tower.atk_speed_original_global =tower.atk_speed_global    --记录原始全局攻击速度加成。

        -- 减慢敌人速度
        -- tower.specialEffect  ='slow'
        -- tower.dec_speed_time  =3
        -- tower.dec_speed_slow  =0.1
        -- tower.dec_speed_slow_global =0.1    -- 全局减速效果
        -- tower.dec_speed_original_global =tower.dec_speed_slow_global
    end
    setmetatable(tower, Tower)
    return tower
end

function Tower:update(enemies, dt,collectAttackData,fireballs)
    self.cooldownTimer = self.cooldownTimer - dt

    
    -- if self.cooldownTimer <= 0 then
    --     for k, enemy in ipairs(enemies) do
    --         if enemy.alive and self:isInRange(enemy) then
    --             self:attack(enemy,k)
    --             self.cooldownTimer = self.attackCooldown
    --             break -- 每次攻击后退出循环
    --         end
    --     end
    -- end
    for i = #self.atkEffects, 1, -1 do
        local effect = self.atkEffects[i]
        effect.duration = effect.duration - dt
        
        if effect.duration <= 0 then
            table.remove(self.atkEffects, i) -- 移除过期的加攻击效果
        end
    end

    -- 加攻击速度因子
    local finalAttackSpeed = 1.0
    for i = #self.atkSpeedEffects, 1, -1 do
        local effect = self.atkSpeedEffects[i]
        effect.duration = effect.duration - dt
        
        if effect.duration <= 0 then
            table.remove(self.atkSpeedEffects, i) -- 移除过期的加攻击速度效果
        else
            finalAttackSpeed = finalAttackSpeed * (1 - effect.addatkspeed)
        end
    end
    -- 实现多个攻击加速效果的叠加和计算。
    if self.atk_speed_global then
        finalAttackSpeed = finalAttackSpeed * (1 - self.atk_speed_global)
    end
    self.atk_speed_add_rate = 1-finalAttackSpeed
    
    local tempatkspeed = self.attackSpeed * (1 - finalAttackSpeed) 
    if self.cooldownTimer <= 0 then
        if  specialEffect  == 'groupattack' then
            -- 塔群体伤害
            for k, enemy in ipairs(enemies) do
                if enemy.alive and self:isInRange(enemy) then
                    self:attack(enemy,collectAttackData)
                 
                end
            end
           

            self.cooldownTimer = 1 / (self.attackSpeed +tempatkspeed )
        else
            -- 塔优先攻击上一次攻击的怪，再次攻击离自己进的怪，
            local target = self:selectTarget(enemies)
            if target then
                self:attack(target,collectAttackData)
                -- 发射火焰弹
                local fireball = Fireball:new(self.x, self.y, target.x,target.y,self.side, 400, self.damage * 2)
                table.insert(fireballs, fireball)
   
                self.cooldownTimer = 1 / (self.attackSpeed +tempatkspeed )
            end
        end
    end
end

function Tower:selectTarget(enemies,collectAttackData)
    -- 优先攻击上一次攻击的怪物
    if self.lastTarget and self.lastTarget.alive then
        local isinrange,distance =self:isInRange(self.lastTarget)
        if isinrange then
            return self.lastTarget
        else

        end
    end

    -- 如果上一次目标不可用，则选择离塔最近的怪物
    local closestEnemy = nil
    local closestDistance = self.range

    for _, enemy in ipairs(enemies) do
        local isinrange,distance =self:isInRange(enemy)
        if enemy.alive and isinrange then
            if distance < closestDistance then
                closestDistance = distance
                closestEnemy = enemy
            end
        end
    end

    return closestEnemy
end
function Tower:isInRange(enemy)
    local distance = math.sqrt((self.x - enemy.x)^2 + (self.y - enemy.y)^2)
    return distance <= self.range,distance
end

function Tower:attack(enemy,collectAttackData)
  

    -- 有几率攻击触发 增加攻击力
    local effect = {
        duration = 3,
        addatk = 0.1
    }
    table.insert(self.atkEffects, effect)

    local finalAtkFactor = 1.0
    -- 实现多个加攻击力效果的叠加和计算。
    for _, atkEffect in ipairs(self.atkEffects) do
        finalAtkFactor = finalAtkFactor * (1 + atkEffect.addatk)
    end
    if self.atk_global then
        finalAtkFactor = finalAtkFactor * (1 + self.atk_global)
    end
    self.atk_add_rate = finalAtkFactor
    local realdamage = self.damage + self.damage*finalAtkFactor



      -- 有几率攻击触发 增加攻击速度
    -- local atk_speed_effect = {
    --     duration = 3,
    --     addatkspeed = 0.1
    -- }
    -- table.insert(self.atkSpeedEffects, atk_speed_effect)





    enemy.health = enemy.health - realdamage

        -- 记录当前帧塔攻击怪物的数据   
    table.insert(collectAttackData, {
        formtowerid = self.towerid,
        formside = self.side,
        toenmeyid = enemy.enmeyid,
        realdamage = realdamage,
    })
    if self.specialEffect == "slow" then
    --     enemy.speed = enemy.speed * 0.5 -- 减慢敌人速度
        -- enemy:applySlow() -- 减速
        enemy:applySlowEffect(self.dec_speed_time, self.dec_speed_slow,self.dec_speed_slow_global) -- 给第一个敌人施加30%的减速，持续5秒,全局减速效果
    end
    if enemy.health <= 0 then
        enemy.health =0
        enemy.alive = false
        -- table.remove(enemies, k) -- 删除敌人
        if self.side ==1 then
            -- playeronescore  =playeronescore  +1
            enemy.deadbyside = self.side
        else
            -- playertwoscore   =playertwoscore  +1
            enemy.deadbyside = self.side
        end
    else
        self.lastTarget = enemy  -- 更新上一次攻击的目标
    end
end
-- function Tower:getplayeronescore()
--     return playeronescore
-- end
-- function Tower:playertwoscore()
--     return playertwoscore
-- end
function Tower:applyEffect(neighboringTowers)
     -- 全局减速效果
    self.dec_speed_slow_global =0
    --减速因子
    local finalSlowFactor = 1.0
    -- 加攻击因子
    local finalAtkFactor = 1.0
    -- 加攻击速度因子
    local finalAttackSpeed = 1.0
    for _, neighbor in ipairs(neighboringTowers) do
        if self.specialEffect == "buffatk" then
            -- 增加攻击力
            finalAtkFactor = finalAtkFactor * (1 + neighbor.atk_original_global)
            self.atk_global=finalAtkFactor
        elseif self.specialEffect == "buffspeed" then
                -- 增加共攻击速度
                finalAttackSpeed = finalAttackSpeed * (1 - neighbor.atk_speed_original_global )
                self.atk_speed_global =finalAttackSpeed

        elseif self.specialEffect == "slow" then
            -- 减速
            -- self.dec_speed_slow_global =self.dec_speed_slow_global +neighbor.dec_speed_original_global
            finalSlowFactor = finalSlowFactor * (1 - neighbor.dec_speed_original_global)
            self.dec_speed_slow_global=finalSlowFactor
        elseif self.specialEffect == "attackSpeed" then
            neighbor:increaseAttackSpeed() -- 增加攻击速度
        end
    end
end


function Tower:increaseAttackSpeed()
    -- 假设有攻击频率属性
    self.attackSpeed = (self.attackSpeed or 1) * 1.5
    print(self.towerType .. "塔的攻击速度提升至: " .. self.attackSpeed)
end
return Tower